package com.memoryangelapplication;

/*
 * 
 * **************Alert Massage Display Event*************
 * Class Includes Functions For
 * 1. Display front end details of an Alert 
 * 2. Capture Alert awaiting time 
 * 3. Capture Event Alert Display time 
 * 4. Schedule next alert 
 * 
 * */
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.memoryangelapplication.global.Event_pass;
import com.memoryangelapplication.model.EventObj;
import com.memoryangelapplication.services.EventAlarm;
import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.PowerManager;
import android.os.Vibrator;
import android.os.PowerManager.WakeLock;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AlertMessageActivitySwipe extends Activity implements
		TextToSpeech.OnInitListener, OnTouchListener {
	int sendCounter;
	 String logTag = null;
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private static final String TAG = null;
	// Master Tables
	JSONArray jArray;
	private String MEM_USER = "table_user";
	private String MEM_EVENT = "table_events";
	String wtever = "What Ever";
	String event_log_id = "";
	String evtTitle = "";
	String evtDate = "";
	String evtTime = "";
	private Activity activity;
	String evtDes = "";
	String event_time_stamp = "";
	String updateEventId;
	String timeSet = "";
	String eventTimeStamp = "";
	int hours;
	int minute;
	int eventListingIndex;
	// Default Settings For Reminders
	String eventremindertime = "";
	String eventremindernumberStr = "";
	String eventwaittime = "";
	Context context;
	ArrayList<EventObj> lst = new ArrayList<EventObj>();
	int delay = 0;
	boolean isFirstTime = true;
	int period = 60000;
	int wait_time;
	int eventwaittimePeriod;
	int event_reminder_time;
	int reminder_number;
	int totalEvents = 0;
	long nextReminderTimeStamp;
	MediaPlayer player;
	public static int counter = 0;
	public static int repeat_counter = 0;
	int eventTTS = 1;
	int eventSoundGap;
	int eventContPlay;
	String EvetFlag = "0000";
	ScheduledThreadPoolExecutor executor;
	ScheduledThreadPoolExecutor executor1;
	Handler handler, main_handelr;
	SoundManager soundManager;
	SoundManager1 soundManager1;
	TextToSpeech talker;
	EditText eventmainid;
	Runnable r1;
	String current_time;
	String newhours = null;
	String newminute;
	String DateSendAct, TimeAct, Tzone,eventTimeStampMain;
	long TimeStampValue;
	String eventPackage;
	String eventURL;
	String eventActionStr;
	int CurrentEventAction = 0;
	int NextEventAction;
	int PreEventAction;
	int eventIndexCounter = 0;
	TextView eventcounter;
	static final int MIN_DISTANCE = 100;// TODO change this runtime based on screen resolution. for 1920x1080 is to small the 100 distance
	private float downX, downY, upX, upY;
	JSONObject eventsItems = null;
	JSONObject eventsArrayObj = null;
	JSONObject eventsArrayObjMain = null;
	String EventsFullRequest,eventnxt_incr,eventTimeStampStr;
	int EventIndex;
	
	ArrayList<String> EventsList = new ArrayList<String>();
	ArrayList<String> EventsListArray = new ArrayList<String>();
	
	public void displayNextActivity(View view) {
		NextEventAction = CurrentEventAction + 1;
		try {
			jArray = new JSONArray(EventsFullRequest);
			JSONObject json_data = null;
			for (int i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				String event_log_id = json_data.getString("event_log_id");
				String event_id = json_data.getString("event_id");
				String event_title = json_data.getString("event_title");
				String event_date = json_data.getString("event_date");
				String event_time = json_data.getString("event_time");
				String event_description = json_data.getString("event_description");
				String event_eventremindertime = json_data.getString("event_eventremindertime");
				String eventReminderNumber = json_data.getString("event_eventremindernumber");
				String eventWaitTime = json_data.getString("event_eventwaittime");
				String EventIndex = json_data.getString("nxt_incr");
				String eventTimeStamp = json_data.getString("eventTimeStamp");
				String eventAction = json_data.getString("eventAction");
				
				Log.e("ALERT LOG 1 = ", "event_log_id:" + event_log_id);
				Log.e("ALERT LOG 2 = ", "event_id    :" + event_id);
				Log.e("ALERT LOG 3 = ", "event_title :" + event_title);
				Log.e("ALERT LOG 4 = ", "event_date  :" + event_date);
				Log.e("ALERT LOG 5 = ", "event_time  :" + event_time);
				Log.e("ALERT LOG 6 = ", "event_description       :" + event_description);
				Log.e("ALERT LOG 7 = ", "event_eventremindertime :" + event_eventremindertime);
				Log.e("ALERT LOG 8 = ", "eventReminderNumber     :" + eventReminderNumber);
				Log.e("ALERT LOG 9 = ", "eventWaitTime           :" + eventWaitTime);
				Log.e("ALERT LOG 10 = ", "EventIndex             :" + EventIndex);
				Log.e("ALERT LOG 11 = ", "eventTimeStamp         :" + eventTimeStamp);
				Log.e("ALERT LOG 12 = ", "eventAction            :" + eventAction);		
				
				eventListingIndex  = Integer.parseInt(EventIndex);
				Log.e(logTag, "RightToLeftSwipe  99999999 :" + NextEventAction);
				Log.e(logTag, "eventListingIndex 99999999 : " + eventListingIndex);
				if(PreEventAction == eventListingIndex){
					Intent i2 = new Intent(AlertMessageActivitySwipe.this, AlertMessageActivity.class);  //your class
					//Intent i2 = new Intent(getBaseContext(), AlertMessageActivity.class);
					i2.putExtra("event_log_id", event_log_id);
					i2.putExtra("event_id", event_id);
					i2.putExtra("event_title", event_title);
					i2.putExtra("event_date", event_date);
					i2.putExtra("event_time",event_time);
					i2.putExtra("event_description", event_description);
					i2.putExtra("event_eventremindertime", event_eventremindertime);
					i2.putExtra("event_eventremindernumber", eventReminderNumber);
					i2.putExtra("event_eventwaittime", eventWaitTime);
					i2.putExtra("nxt_incr", "2");
					i2.putExtra("eventTimeStamp", eventTimeStamp);
					i2.putExtra("eventAction", PreEventAction);
					
					executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);
					AlertMessageActivitySwipe.this.finish();
					i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(i2);
					finish();
				}
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void displayPreviousActivity(View view) {
		PreEventAction = CurrentEventAction - 1;
		try {
			jArray = new JSONArray(EventsFullRequest);
			JSONObject json_data = null;
			for (int i = 0; i < jArray.length(); i++) {
				json_data = jArray.getJSONObject(i);
				String event_log_id = json_data.getString("event_log_id");
				String event_id = json_data.getString("event_id");
				String event_title = json_data.getString("event_title");
				String event_date = json_data.getString("event_date");
				String event_time = json_data.getString("event_time");
				String event_description = json_data.getString("event_description");
				String event_eventremindertime = json_data.getString("event_eventremindertime");
				String eventReminderNumber = json_data.getString("event_eventremindernumber");
				String eventWaitTime = json_data.getString("event_eventwaittime");
				String EventIndex = json_data.getString("nxt_incr");
				String eventTimeStamp = json_data.getString("eventTimeStamp");
				String eventAction = json_data.getString("eventAction");
				
				Log.e("ALERT LOG 1 = ", "event_log_id:" + event_log_id);
				Log.e("ALERT LOG 2 = ", "event_id    :" + event_id);
				Log.e("ALERT LOG 3 = ", "event_title :" + event_title);
				Log.e("ALERT LOG 4 = ", "event_date  :" + event_date);
				Log.e("ALERT LOG 5 = ", "event_time  :" + event_time);
				Log.e("ALERT LOG 6 = ", "event_description       :" + event_description);
				Log.e("ALERT LOG 7 = ", "event_eventremindertime :" + event_eventremindertime);
				Log.e("ALERT LOG 8 = ", "eventReminderNumber     :" + eventReminderNumber);
				Log.e("ALERT LOG 9 = ", "eventWaitTime           :" + eventWaitTime);
				Log.e("ALERT LOG 10 = ", "EventIndex             :" + EventIndex);
				Log.e("ALERT LOG 11 = ", "eventTimeStamp         :" + eventTimeStamp);
				Log.e("ALERT LOG 12 = ", "eventAction            :" + eventAction);		
				eventListingIndex  = Integer.parseInt(EventIndex);
				Log.e(logTag, "LeftToRightSwipe  6666666 : " + PreEventAction);
				Log.e(logTag, "eventListingIndex 6666666 : " + eventListingIndex);
				
				
				if(NextEventAction == eventListingIndex){
					Intent i2 = new Intent(AlertMessageActivitySwipe.this, AlertMessageActivity.class);  //your class
					//Intent i2 = new Intent(getBaseContext(), AlertMessageActivity.class);
					i2.putExtra("event_log_id", event_log_id);
					i2.putExtra("event_id", event_id);
					i2.putExtra("event_title", event_title);
					i2.putExtra("event_date", event_date);
					i2.putExtra("event_date",event_time);
					i2.putExtra("event_description", event_description);
					i2.putExtra("event_eventremindertime", event_eventremindertime);
					i2.putExtra("event_eventremindernumber", eventReminderNumber);
					i2.putExtra("event_eventwaittime", eventWaitTime);
					i2.putExtra("nxt_incr", "2");
					i2.putExtra("eventTimeStamp", eventTimeStamp);
					i2.putExtra("eventAction", NextEventAction);
					
	
					
					executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);
					AlertMessageActivitySwipe.this.finish();
					i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(i2);
					finish();
				}
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//Remove title bar
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    //Remove notification bar
	    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.event_values);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		getWindow().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
		
		KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);  
		KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE); 
		lock.disableKeyguard();
		
		
		context = AlertMessageActivitySwipe.this;
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		WakeLock wakeLock = powerManager.newWakeLock(
				PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
		wakeLock.acquire();

		eventcounter = (TextView) findViewById(R.id.eventcounter);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			event_log_id = bundle.getString("event_log_id");
			updateEventId = bundle.getString("event_id");
			evtTitle = bundle.getString("event_title");
			evtDate = bundle.getString("event_date");
			evtTime = bundle.getString("event_time");
			evtDes = bundle.getString("event_description");
			eventremindertime = bundle.getString("event_eventremindertime");
			eventremindernumberStr = bundle.getString("event_eventremindernumber");
			eventwaittime = bundle.getString("event_eventwaittime");
			eventnxt_incr = bundle.getString("nxt_incr");
			eventTimeStampStr = bundle.getString("eventTimeStamp");
			eventActionStr= bundle.getString("eventAction");//1
			
			try{
				EventIndex = Integer.parseInt(eventnxt_incr);
				eventTimeStampMain = eventTimeStampStr.trim();
				event_reminder_time = Integer.parseInt(eventremindertime);
				reminder_number = Integer.parseInt(eventremindernumberStr);
				eventwaittimePeriod = Integer.parseInt(eventwaittime);
				CurrentEventAction = Integer.parseInt(eventActionStr);
			}
			catch(Exception e){
				Log.e("@@@@@@@@(1000)", "Exception" + e);
				EventIndex = 2;
				event_reminder_time = 2;
				reminder_number = 2;
				eventwaittimePeriod = 2;
				CurrentEventAction = 2;
			}
			Log.e("ALERT LOG 1 =  ", "event_log_id:" + event_log_id);
			Log.e("ALERT LOG 2 =  ", "updateEventId:" + updateEventId);
			Log.e("ALERT LOG 3 =  ", "evtTitle:" + evtTitle);
			Log.e("ALERT LOG 4 =  ", "evtDate:" + evtDate);
			Log.e("ALERT LOG 5 =  ", "evtTime:" + evtTime);
			Log.e("ALERT LOG 6 =  ", "evtDes:" + evtDes);
			Log.e("ALERT LOG 7 =  ", "eventremindertime:" + eventremindertime);
			Log.e("ALERT LOG 8 =  ", "eventremindernumberStr:" + eventremindernumberStr);
			Log.e("ALERT LOG 9 =  ", "eventwaittime:" + eventwaittime);
			Log.e("ALERT LOG 10 = ", "eventnxt_incr:" + eventnxt_incr);
			Log.e("ALERT LOG 11 = ", "eventTimeStamp:" + eventTimeStamp);
			Log.e("ALERT LOG 12 = ", "eventAction:" + eventActionStr);

			
		}
		checkMutipleEvents(); 
		

		wait_time = eventwaittimePeriod * 1000;

		// Time Zone Of the Current Phone
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
				Locale.getDefault());
		Date currentLocalTime = calendar.getTime();
		DateFormat date = new SimpleDateFormat("Z");
		Tzone = date.format(currentLocalTime);
		Tzone = " " + Tzone;
		String currentTime = getAddDateTimeStringPreCheck();
		String[] CheckDayTime = currentTime.split(" ");
		DateSendAct = CheckDayTime[0];
		TimeAct = CheckDayTime[1];
		getNativeTimeStamp(DateSendAct, TimeAct, Tzone);

		
		
		String nxtIcrs = bundle.getString("nxt_incr");

		final int nxtIcr = Integer.parseInt(nxtIcrs);

		// Schedule Events Threads Handling Sounds and Display
		executor = new ScheduledThreadPoolExecutor(1);
		executor1 = new ScheduledThreadPoolExecutor(1);

		talker = new TextToSpeech(this, this);
		main_handelr = new Handler();

		new CountDownTimer(wait_time, 1000) {
			public void onTick(long millisUntilFinished) {
				Log.e("Timmer Started", "Timmer Started");
			}

			public void onFinish() {
				executor.shutdown();
				executor.shutdownNow();
				executor.remove(soundManager);

				executor1.shutdown();
				executor1.shutdownNow();
				executor1.remove(soundManager1);
				eventDetailsUpdate();
				setNextReminder();
				AlertMessageActivitySwipe.this.finish();
			}
		}.start();
		// for viberating and using media player
		try {
			Vibrator myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
			myVib.vibrate(3000);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

		// How many times alert need to be display
		if (reminder_number == 0) {
			reminder_number = 3;

		}
		// Reminder Delay
		if (event_reminder_time == 0) {
			event_reminder_time = 60;

		}
		// Display Reminder
		if (wait_time == 0) {
			// if 0 then default will be 5
			wait_time = 45 * 1000;
		}
		eventTTS = 1;
		eventContPlay = 1;
		eventSoundGap = 1000;

		if (eventSoundGap == 0) {
			eventSoundGap = 5;
		}
		// Media Player handling events
		if (eventTTS == 1 && eventContPlay == 1) {
			AlertMessageActivitySwipe.counter++;
			soundManager = new SoundManager();
			executor.scheduleAtFixedRate(soundManager, 0, 3000,
					TimeUnit.MILLISECONDS);

		} else if (eventTTS == 1 && eventContPlay == 0) {
			if (AlertMessageActivitySwipe.counter == 0) {

				AlertMessageActivitySwipe.counter++;
				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";
				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivitySwipe.this, R.raw.alarm);
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
						Handler handler = new Handler();
						final Runnable r = new Runnable() {
							public void run() {
								String text = evtDes;
								talker.speak(text, TextToSpeech.QUEUE_FLUSH,
										null);
							}
						};
						handler.postDelayed(r, 3000);
					}
				});
			}

		} else if (eventTTS == 0 && eventContPlay == 1) {
			soundManager1 = new SoundManager1();
			executor1.scheduleAtFixedRate(soundManager1, 0, 3000,
					TimeUnit.MILLISECONDS);
		} else if (eventTTS == 0 && eventContPlay == 0) {

			if (AlertMessageActivitySwipe.counter == 0) {

				AlertMessageActivitySwipe.counter++;

				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivitySwipe.this, R.raw.alarm);
				// we start playing the file!
				player.start();
				player.setOnCompletionListener(new OnCompletionListener() {
					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();
					}

				});

			}

		}
		
		
		
		// Front end display events details
		RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.alert_layout);
		rlayout.setOnTouchListener(new OnTouchListener() {
			 public void RelativeLayoutTouchListener(AlertMessageActivitySwipe mainActivity) {
			        activity = mainActivity;  
			    }
			 
			/* public void onRightToLeftSwipe() {
				    PreEventAction = CurrentEventAction + 1;
					Log.e(logTag, "RightToLeftSwipe 99999999");
			      //  Toast.makeText(activity, "RightToLeftSwipe", Toast.LENGTH_SHORT).show();
			        // activity.doSomething();
					try {
						jArray = new JSONArray(EventsFullRequest);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							String event_log_id = json_data.getString("event_log_id");
							String event_id = json_data.getString("event_id");
							String event_title = json_data.getString("event_title");
							String event_date = json_data.getString("event_date");
							String event_time = json_data.getString("event_time");
							String event_description = json_data.getString("event_description");
							String event_eventremindertime = json_data.getString("event_eventremindertime");
							String eventReminderNumber = json_data.getString("event_eventremindernumber");
							String eventWaitTime = json_data.getString("event_eventwaittime");
							String EventIndex = json_data.getString("nxt_incr");
							String eventTimeStamp = json_data.getString("eventTimeStamp");
							String eventAction = json_data.getString("eventAction");
							
							Log.e("ALERT LOG 1 = ", "event_log_id:" + event_log_id);
							Log.e("ALERT LOG 2 = ", "event_id    :" + event_id);
							Log.e("ALERT LOG 3 = ", "event_title :" + event_title);
							Log.e("ALERT LOG 4 = ", "event_date  :" + event_date);
							Log.e("ALERT LOG 5 = ", "event_time  :" + event_time);
							Log.e("ALERT LOG 6 = ", "event_description       :" + event_description);
							Log.e("ALERT LOG 7 = ", "event_eventremindertime :" + event_eventremindertime);
							Log.e("ALERT LOG 8 = ", "eventReminderNumber     :" + eventReminderNumber);
							Log.e("ALERT LOG 9 = ", "eventWaitTime           :" + eventWaitTime);
							Log.e("ALERT LOG 10 = ", "EventIndex             :" + EventIndex);
							Log.e("ALERT LOG 11 = ", "eventTimeStamp         :" + eventTimeStamp);
							Log.e("ALERT LOG 12 = ", "eventAction            :" + eventAction);		
							
							eventListingIndex  = Integer.parseInt(EventIndex);
							if(PreEventAction == eventListingIndex){
								Intent i2 = new Intent(AlertMessageActivitySwipe.this, AlertMessageActivity.class);  //your class
								//Intent i2 = new Intent(getBaseContext(), AlertMessageActivity.class);
								i2.putExtra("event_log_id", event_log_id);
								i2.putExtra("event_id", event_id);
								i2.putExtra("event_title", event_title);
								i2.putExtra("event_date", event_date);
								i2.putExtra("event_time",event_time);
								i2.putExtra("event_description", event_description);
								i2.putExtra("event_eventremindertime", event_eventremindertime);
								i2.putExtra("event_eventremindernumber", eventReminderNumber);
								i2.putExtra("event_eventwaittime", eventWaitTime);
								i2.putExtra("nxt_incr", PreEventAction);
								i2.putExtra("eventTimeStamp", eventTimeStamp);
								i2.putExtra("eventAction", PreEventAction);
								
								executor.shutdown();
								executor.shutdownNow();
								executor.remove(soundManager);

								executor1.shutdown();
								executor1.shutdownNow();
								executor1.remove(soundManager1);
								AlertMessageActivitySwipe.this.finish();
								i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(i2);
								finish();
							}
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					
				
			    }*/

			   /* public void onLeftToRightSwipe() {
			    	NextEventAction = CurrentEventAction - 1;
			        Log.e(logTag, "LeftToRightSwipe 6666666");
			        
					try {
						jArray = new JSONArray(EventsFullRequest);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							
						
							
							json_data = jArray.getJSONObject(i);
							String event_log_id = json_data.getString("event_log_id");
							String event_id = json_data.getString("event_id");
							String event_title = json_data.getString("event_title");
							String event_date = json_data.getString("event_date");
							String event_time = json_data.getString("event_time");
							String event_description = json_data.getString("event_description");
							String event_eventremindertime = json_data.getString("event_eventremindertime");
							String eventReminderNumber = json_data.getString("event_eventremindernumber");
							String eventWaitTime = json_data.getString("event_eventwaittime");
							String EventIndex = json_data.getString("nxt_incr");
							String eventTimeStamp = json_data.getString("eventTimeStamp");
							String eventAction = json_data.getString("eventAction");
							
							Log.e("ALERT LOG 1 = ", "event_log_id:" + event_log_id);
							Log.e("ALERT LOG 2 = ", "event_id    :" + event_id);
							Log.e("ALERT LOG 3 = ", "event_title :" + event_title);
							Log.e("ALERT LOG 4 = ", "event_date  :" + event_date);
							Log.e("ALERT LOG 5 = ", "event_time  :" + event_time);
							Log.e("ALERT LOG 6 = ", "event_description       :" + event_description);
							Log.e("ALERT LOG 7 = ", "event_eventremindertime :" + event_eventremindertime);
							Log.e("ALERT LOG 8 = ", "eventReminderNumber     :" + eventReminderNumber);
							Log.e("ALERT LOG 9 = ", "eventWaitTime           :" + eventWaitTime);
							Log.e("ALERT LOG 10 = ", "EventIndex             :" + EventIndex);
							Log.e("ALERT LOG 11 = ", "eventTimeStamp         :" + eventTimeStamp);
							Log.e("ALERT LOG 12 = ", "eventAction            :" + eventAction);		
							eventListingIndex  = Integer.parseInt(EventIndex);
							if(NextEventAction == eventListingIndex){
								Intent i2 = new Intent(AlertMessageActivitySwipe.this, AlertMessageActivity.class);  //your class
								//Intent i2 = new Intent(getBaseContext(), AlertMessageActivity.class);
								i2.putExtra("event_log_id", event_log_id);
								i2.putExtra("event_id", event_id);
								i2.putExtra("event_title", event_title);
								i2.putExtra("event_date", event_date);
								i2.putExtra("event_time",event_time);
								i2.putExtra("event_description", event_description);
								i2.putExtra("event_eventremindertime", event_eventremindertime);
								i2.putExtra("event_eventremindernumber", eventReminderNumber);
								i2.putExtra("event_eventwaittime", eventWaitTime);
								i2.putExtra("nxt_incr", NextEventAction);
								i2.putExtra("eventTimeStamp", eventTimeStamp);
								i2.putExtra("eventAction", NextEventAction);
								
								executor.shutdown();
								executor.shutdownNow();
								executor.remove(soundManager);

								executor1.shutdown();
								executor1.shutdownNow();
								executor1.remove(soundManager1);
								AlertMessageActivitySwipe.this.finish();
								i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								startActivity(i2);
								finish();
							}
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
			    }*/

			    public void onTopToBottomSwipe() {
			        Log.i(logTag, "onTopToBottomSwipe!");
			       // Toast.makeText(activity, "onTopToBottomSwipe", Toast.LENGTH_SHORT).show();
			        // activity.doSomething();
			        lst = Event_pass.getData();
					if (lst != null && lst.size() > nxtIcr) {

						EventObj mth = (EventObj) lst.get(nxtIcr);
						if (lst != null) {
							Intent i2 = new Intent(getApplicationContext(),
									AlertMessageActivitySwipe.class);

							event_log_id = mth.getEvent_event_log_id();
							Log.v("LOG -", "ALAM ID : " + updateEventId);
							i2.putExtra("event_id", mth.getEvent_time_stamp());
							i2.putExtra("event_title", mth.getEvent_title());
							i2.putExtra("event_date", mth.getEvent_date());
							i2.putExtra("event_time", mth.getEvent_time());
							i2.putExtra("event_description",
									mth.getEvent_description());
							i2.putExtra("eventremindertime",
									mth.getEvent_eventremindertime());
							i2.putExtra("eventremindernumber",
									mth.getEvent_eventremindernumber());
							i2.putExtra("eventwaittime",
									mth.getEvent_eventwaittime());
							i2.putExtra("nxt_incr", "" + (nxtIcr + 1));
							startActivity(i2);
						}
					} else {

					}

					executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);
				
					updateState();
			    }

			    public void onBottomToTopSwipe() {
			        Log.i(logTag, "onBottomToTopSwipe!");
			      //  Toast.makeText(activity, "onBottomToTopSwipe", Toast.LENGTH_SHORT).show();
			        // activity.doSomething();
			        lst = Event_pass.getData();
					if (lst != null && lst.size() > nxtIcr) {

						EventObj mth = (EventObj) lst.get(nxtIcr);
						if (lst != null) {
							Intent i2 = new Intent(getApplicationContext(),
									AlertMessageActivitySwipe.class);

							event_log_id = mth.getEvent_event_log_id();
							Log.v("LOG -", "ALAM ID : " + updateEventId);
							i2.putExtra("event_id", mth.getEvent_time_stamp());
							i2.putExtra("event_title", mth.getEvent_title());
							i2.putExtra("event_date", mth.getEvent_date());
							i2.putExtra("event_time", mth.getEvent_time());
							i2.putExtra("event_description",
									mth.getEvent_description());
							i2.putExtra("eventremindertime",
									mth.getEvent_eventremindertime());
							i2.putExtra("eventremindernumber",
									mth.getEvent_eventremindernumber());
							i2.putExtra("eventwaittime",
									mth.getEvent_eventwaittime());
							i2.putExtra("nxt_incr", "" + (nxtIcr + 1));
							startActivity(i2);
						}
					} else {

					}

					executor.shutdown();
					executor.shutdownNow();
					executor.remove(soundManager);

					executor1.shutdown();
					executor1.shutdownNow();
					executor1.remove(soundManager1);
					updateState();
			    }

			    public boolean onTouch(View v, MotionEvent event) {
			        switch (event.getAction()) {
			        case MotionEvent.ACTION_DOWN: {
			            downX = event.getX();
			            downY = event.getY();
			            return true;
			        }
			        case MotionEvent.ACTION_UP: {
			            upX = event.getX();
			            upY = event.getY();

			            float deltaX = downX - upX;
			            float deltaY = downY - upY;

			            // swipe horizontal?
			            if (Math.abs(deltaX) > MIN_DISTANCE) {
			                // left or right
			                if (deltaX < 0) {
			                  //  this.onLeftToRightSwipe();
			                    return true;
			                }
			                if (deltaX > 0) {
			                  //  this.onRightToLeftSwipe();
			                    return true;
			                }
			            } else {
			                Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long horizontally, need at least " + MIN_DISTANCE);
			                // return false; // We don't consume the event
			            }

			            // swipe vertical?
			            if (Math.abs(deltaY) > MIN_DISTANCE) {
			                // top or down
			                if (deltaY < 0) {
			                    this.onTopToBottomSwipe();
			                    return true;
			                }
			                if (deltaY > 0) {
			                    this.onBottomToTopSwipe();
			                    return true;
			                }
			            } else {
			                Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long vertically, need at least " + MIN_DISTANCE);
			                // return false; // We don't consume the event
			            }

			            return false; // no swipe horizontally and no swipe vertically
			        }// case MotionEvent.ACTION_UP:
			        }
			        return false;
			    }
		});
		
		eventmainid = (EditText) findViewById(R.id.eventmainid);
		TextView EvtDate = (TextView) findViewById(R.id.reminder_date);
		TextView EvtTime = (TextView) findViewById(R.id.reminder_time);
		TextView EvtTitle = (TextView) findViewById(R.id.title);
		TextView EvtDes = (TextView) findViewById(R.id.description);
		eventmainid.setText(event_log_id);
		EvtTitle.setText(evtTitle);
		EvtDate.setText(evtDate);
		EvtTime.setText(evtTime);
		EvtDes.setText(evtDes);

	}

	private void checkMutipleEvents() {
		Log.e(logTag, "checkMutipleEvents:***************("  + eventActionStr + ")***************" + eventTimeStampMain);
		// TODO Auto-generated method stub
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		ContentValues newrowfDealer = new ContentValues();
		Cursor fdealerrows = null;
		try {
			String query = "SELECT * FROM table_events WHERE eventTimeStamp = '" + eventTimeStampMain + "' AND event_active = '0'";
			fdealerrows = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (fdealerrows != null) {
			if (fdealerrows.getCount() > 0) {
				eventIndexCounter = 0;
				while (fdealerrows.moveToNext()) {
					String event_log_id = fdealerrows.getString(1);
					String event_user_id = fdealerrows.getString(2);
					String event_title = fdealerrows.getString(3);
					String event_description = fdealerrows.getString(4);
					String event_status = fdealerrows.getString(5);
					String event_date = fdealerrows.getString(6);
					String event_time = fdealerrows.getString(7);
					String event_alam_time = fdealerrows.getString(8);
					String event_active = fdealerrows.getString(9);
					String eventReminderTime = fdealerrows.getString(16);
					String eventReminderNumber = fdealerrows.getString(17);
					String eventWaitTime = fdealerrows.getString(18);
					String eventTimeStamp = fdealerrows.getString(20);
					
					Log.v("LOG -", "(1) : " + event_log_id);
					Log.v("LOG -", "(2) : " + event_user_id);
					Log.v("LOG -", "(3) : " + event_title);
					Log.v("LOG -", "(4) : " + event_description);
					Log.v("LOG -", "(5) : " + event_status);
					Log.v("LOG -", "(6) : " + event_date);
					Log.v("LOG -", "(7) : " + event_time);
					Log.v("LOG -", "(8) : " + event_alam_time);
					Log.v("LOG -", "(9) : " + event_active);
					Log.v("LOG -", "(10) : " + eventReminderTime);
					Log.v("LOG -", "(11) : " + eventReminderNumber);
					Log.v("LOG -", "(12) : " + eventWaitTime);
					Log.v("LOG -", "(13) : " + eventTimeStamp);
					
					eventsItems = new JSONObject();
					//HashMap<String, String> map = new HashMap<String, String>();
					eventIndexCounter = eventIndexCounter + 1;
					try{
						//eventsItems.put("eventIndex", eventIndex);
						eventsItems.put("event_log_id", event_log_id);
						eventsItems.put("event_id", event_alam_time);
						eventsItems.put("event_title", event_title);
						eventsItems.put("event_date", event_date);
						eventsItems.put("event_time", event_time);
						eventsItems.put("event_description", event_description);
						eventsItems.put("event_eventremindertime", eventReminderTime);
						eventsItems.put("event_eventremindernumber", eventReminderNumber);
						eventsItems.put("event_eventwaittime", eventWaitTime);
						EventIndex = EventIndex + 1;
						eventsItems.put("nxt_incr", EventIndex);
						eventsItems.put("eventTimeStamp", eventTimeStamp);
						eventsItems.put("eventAction", eventActionStr);
						EventsList.add(eventsItems.toString());
					}
					catch(Exception e){
						Log.v("LOG -", "Exception(100) : " + e);
					}
				}
			}
		}
		
		Log.v("LOG - 1:", "EVENTS(100) = " + EventsList.toString());
		Log.v("*********", "*************************************");
		Log.v("LOG - 2:", "EVENTS(100) = " + "{\"EventsAll\":" + EventsList.toString()+"}");
		//EventsFullRequest = "{\"EventsAll\":" + EventsList.toString()+"}";
		EventsFullRequest = EventsList.toString();
		
		
		/*eventsArrayObj = new JSONObject();
		eventsArrayObjMain = new JSONObject();
		try {
			eventsArrayObj.put("Items",""+totalEvents);
			eventsArrayObj.put("Events",EventsList.toString().replaceAll("/", ""));
			EventsListArray.add(eventsArrayObj.toString().replaceAll("/", ""));
			
			eventsArrayObjMain.put("EventsMain", EventsListArray.toString());
			String bookingFormata = eventsArrayObjMain.toString();
			
			Log.e(logTag, "bookingFormata :" + bookingFormata);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		
	
		//eventcounter.setText("1 of 5 Events");
		eventcounter.setText("1 of " + eventIndexCounter + " Events");
	}

	public long getNativeTimeStamp(String DateSend, String Time, String Tzone) {
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm zzzzz");
		Calendar c = Calendar.getInstance();
		Date d = null;

		try {
			d = ddMMMyyFormat
					.parse(DateSend.trim() + " " + Time.trim() + Tzone);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		c.setTime(d);

		String date_to_string = ddMMMyyFormat
				.format(c.getTimeInMillis() / 1000);
		TimeStampValue = c.getTimeInMillis() / 1000;
		return c.getTimeInMillis() / 1000;
	}

	protected void setNextReminder() {
		Bundle bundle = new Bundle();
		EventAlarm alarm1 = new EventAlarm(context, bundle, event_reminder_time);
	}

	private void eventDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {
			String query = "SELECT * FROM table_events WHERE event_log_id = 'event_log_id'";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// Don't forget to shutdown!
		if (talker != null) {
			talker.stop();
			talker.shutdown();
		}

	}

	class SoundManager implements Runnable {

		int counter = 0;

		@Override
		public void run() {

			if ((counter % 2) == 0) {

				setVolumeControlStream(AudioManager.STREAM_MUSIC);
				// our file here is in fact called "soundfile.mp3";

				MediaPlayer player = MediaPlayer.create(
						AlertMessageActivitySwipe.this, R.raw.alarm);
				// we start playing the file!
				player.start();

				player.setOnCompletionListener(new OnCompletionListener() {

					@Override
					public void onCompletion(MediaPlayer mp) {
						mp.stop();
						mp.release();

					}
				});

			} else if ((counter % 2) != 0) {
				String text = evtDes;
				talker.speak(text, TextToSpeech.QUEUE_FLUSH, null);
			}
			counter++;
		}

	}

	class SoundManager1 implements Runnable {

		@Override
		public void run() {

			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			// our file here is in fact called "soundfile.mp3";

			MediaPlayer player = MediaPlayer.create(AlertMessageActivitySwipe.this,
					R.raw.alarm);
			// we start playing the file!
			player.start();

			player.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.stop();
					mp.release();
				}
			});
		}

	}

	protected void updateState() {
		// TODO Auto-generated method stub
		if(event_log_id == null || event_log_id.equals("")){
			event_log_id = eventmainid.getText().toString().trim();
		}
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEvents = null;
		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_url,event_package FROM table_events Where event_log_id = '"
					+ event_log_id + "'";
			checkPreEvents = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEvents != null) {
			if (checkPreEvents.getCount() > 0) {
				while (checkPreEvents.moveToNext()) {
					ContentValues updateEvets = new ContentValues();
					String updateID = checkPreEvents.getString(0);
					eventURL = checkPreEvents.getString(3);
					eventPackage = checkPreEvents.getString(4);

					updateEvets.put("event_status", "3");
					updateEvets.put("event_active", "1");
					updateEvets.put("event_update_time", getAddDateTimeString()
							.toString());
					mydb.update(MEM_EVENT, updateEvets, "event_log_id ='"
							+ updateID + "'", null);
				}
			}
		}
		checkPreEvents.close();
		mydb.close();
		
		Log.e("REQUEST 1:", "VAL PASS 1 :" +eventURL);
		Log.e("REQUEST 2:", "VAL PASS 2 :" +eventPackage);
		
		if (eventPackage.equals("404") && eventURL.equals("404")) {
			closeExcecutor();
			AlertMessageActivitySwipe.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		} else if (!eventURL.equals("404")) {
			try {
				Log.e("REQUEST :", "Fire URL**********");
				closeExcecutor();
				Intent viewIntent = new Intent("android.intent.action.VIEW",
						Uri.parse(eventURL.trim()));
				viewIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                         | Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(viewIntent);
				AlertMessageActivitySwipe.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
			} catch (Exception e) {

			}
		} else if (!eventPackage.equals("404")) {
			Log.e("REQUEST :", "Fire Package************");
			closeExcecutor();
			Intent i = new Intent(Intent.ACTION_MAIN);
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_NEW_TASK);
			PackageManager managerclock = getPackageManager();
			i = managerclock.getLaunchIntentForPackage(eventPackage.trim());
			i.addCategory(Intent.CATEGORY_LAUNCHER);
			startActivity(i);
			AlertMessageActivitySwipe.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		else{
			closeExcecutor();
			AlertMessageActivitySwipe.this.finish();
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());
		}
		/*
		 * //Allow To Trigger If Previous Events Excisting Bundle bundle = new
		 * Bundle(); EventAlarm alarm1 = new EventAlarm(this, bundle, 1);
		 */
	}

	private void closeExcecutor() {
		// TODO Auto-generated method stub
		executor.shutdown();
		executor.shutdownNow();
		executor.remove(soundManager);

		executor1.shutdown();
		executor1.shutdownNow();
		executor1.remove(soundManager1);
	}

	protected void eventDetailsUpdate() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor checkPreEventsAckCount = null;

		try {
			String query = "SELECT event_log_id,event_time_stamp,event_alam_time,event_ack_count,eventReminderTime,eventReminderNumber,eventWaitTime,eventTimeStamp FROM table_events Where event_alam_time = '"
					+ updateEventId + "'";
			checkPreEventsAckCount = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}
		if (checkPreEventsAckCount != null) {
			if (checkPreEventsAckCount.getCount() > 0) {
				while (checkPreEventsAckCount.moveToNext()) {
					ContentValues updateEvetsCount = new ContentValues();
					String updateID = checkPreEventsAckCount.getString(0);
					String event_alam_time = checkPreEventsAckCount
							.getString(2);
					long event_alam_timecount = Long.parseLong(event_alam_time);

					String updateCounter = checkPreEventsAckCount.getString(3);
					String eventReminderTime = checkPreEventsAckCount
							.getString(4);
					String eventReminderNumber = checkPreEventsAckCount
							.getString(5);
					String eventWaitTime = checkPreEventsAckCount.getString(6);
					String eventCurrentTimeStamp = checkPreEventsAckCount
							.getString(7);

					int eventReminderNumbercount = Integer
							.parseInt(eventReminderNumber);
					// Event Reminder Time = Time 1
					long eventReminderTimecount = Long
							.parseLong(eventReminderTime);
					long eventeventWaitTimecount = Long
							.parseLong(eventWaitTime);
					long eventeventCurrentTimeStamp = Long
							.parseLong(eventCurrentTimeStamp);

					long curCount = Long.parseLong(updateCounter);
					curCount = curCount + 1;

					long newEventCurrentTimeStamp = (eventReminderTimecount + eventeventWaitTimecount)
							* curCount;
					newEventCurrentTimeStamp = newEventCurrentTimeStamp
							+ TimeStampValue;
					String newEventCurrentTimeStampStr = String
							.valueOf(newEventCurrentTimeStamp);

					if (eventReminderNumbercount == curCount) {
						updateEvetsCount.put("event_status", "4");
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_active", "1");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);

						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					} else {
						nextReminderTimeStamp = newEventCurrentTimeStamp;
						newEventCurrentTimeStampStr = String.valueOf(nextReminderTimeStamp);
						updateEvetsCount.put("event_ack_count", curCount);
						updateEvetsCount.put("event_status", "9");
						updateEvetsCount.put("event_alam_time", newEventCurrentTimeStampStr);
						mydb.update(MEM_EVENT, updateEvetsCount,
								"event_log_id ='" + updateID + "'", null);
					}

				}
			}
		}
		checkPreEventsAckCount.close();
		mydb.close();

	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub

	}

	// Used to convert 24hr format to 12hr format with AM/PM values
	private void updateTime(int hours, int mins) {

		if (hours > 12) {
			hours -= 12;
			timeSet = "PM";
		} else if (hours == 0) {
			hours += 12;
			timeSet = "AM";
		} else if (hours == 12)
			timeSet = "PM";
		else
			timeSet = "AM";

		String minutes = "";
		if (mins < 10)
			minutes = "0" + mins;
		else
			minutes = String.valueOf(mins);

		// Append in a StringBuilder
		String aTime = new StringBuilder().append(hours).append(':')
				.append(minutes).append(" ").append(timeSet).toString();
		// output.setText(aTime);
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAddDateTimeStringPreCheck() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return false;
	}
}
